<template>
  <div class="prediction-detail-panel">
    <!-- 用户基本信息 -->
    <div class="user-info-section">
      <h3>用户基本信息</h3>
      <el-row :gutter="24">
        <el-col :span="12">
          <div class="info-item">
            <span class="label">用户ID:</span>
            <span class="value">{{ prediction.userId }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户姓名:</span>
            <span class="value">{{ prediction.userName }}</span>
          </div>
          <div class="info-item">
            <span class="label">购买意向:</span>
            <el-tag :type="getIntentTagType(prediction.intentLevel)">
              {{ getIntentLevelText(prediction.intentLevel) }}
            </el-tag>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info-item">
            <span class="label">购买概率:</span>
            <span class="value">{{ Math.round(prediction.purchaseProbability * 100) }}%</span>
          </div>
          <div class="info-item">
            <span class="label">预测购买时间:</span>
            <span class="value">{{ prediction.predictedDate }}</span>
          </div>
          <div class="info-item">
            <span class="label">预测金额:</span>
            <span class="value">¥{{ prediction.predictedAmount.toLocaleString() }}</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 购买预测详情 -->
    <div class="prediction-details-section">
      <h3>购买预测详情</h3>
      <el-row :gutter="24">
        <el-col :span="12">
          <div class="detail-card">
            <h4>预测时间分析</h4>
            <div class="time-analysis">
              <div class="time-item">
                <span class="time-label">最可能购买时间:</span>
                <span class="time-value">{{ prediction.predictedDate }}</span>
              </div>
              <div class="time-item">
                <span class="time-label">时间置信度:</span>
                <el-progress :percentage="timeConfidence" :stroke-width="8" />
              </div>
              <div class="time-item">
                <span class="time-label">购买窗口期:</span>
                <span class="time-value">{{ getPurchaseWindow() }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="detail-card">
            <h4>金额预测分析</h4>
            <div class="amount-analysis">
              <div class="amount-item">
                <span class="amount-label">预测金额:</span>
                <span class="amount-value">¥{{ prediction.predictedAmount.toLocaleString() }}</span>
              </div>
              <div class="amount-item">
                <span class="amount-label">金额置信度:</span>
                <el-progress :percentage="amountConfidence" :stroke-width="8" />
              </div>
              <div class="amount-item">
                <span class="amount-label">金额范围:</span>
                <span class="amount-value">{{ getAmountRange() }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 影响因子分析 -->
    <div class="factors-section" v-if="prediction.factors">
      <h3>影响因子分析</h3>
      <div class="factors-grid">
        <div 
          v-for="factor in prediction.factors" 
          :key="factor.name"
          class="factor-card"
          :class="factor.impact"
        >
          <div class="factor-header">
            <span class="factor-name">{{ factor.name }}</span>
            <span class="factor-impact">{{ getImpactText(factor.impact) }}</span>
          </div>
          <div class="factor-value">
            <el-progress 
              :percentage="factor.value" 
              :stroke-width="8"
              :color="getImpactColor(factor.impact)"
            />
            <span class="value-text">{{ factor.value }}%</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 推荐产品 -->
    <div class="recommended-products-section">
      <h3>推荐产品</h3>
      <div class="products-list">
        <div 
          v-for="product in recommendedProducts" 
          :key="product.id"
          class="product-card"
        >
          <img :src="product.image" :alt="product.name" class="product-image" />
          <div class="product-info">
            <h4>{{ product.name }}</h4>
            <p class="product-category">{{ product.category }}</p>
            <p class="product-price">¥{{ product.price.toLocaleString() }}</p>
          </div>
          <div class="product-metrics">
            <div class="metric">
              <span class="metric-label">推荐度</span>
              <el-rate 
                v-model="product.recommendation" 
                disabled 
                show-score 
                text-color="#ff9900"
                score-template="{value}"
              />
            </div>
            <div class="metric">
              <span class="metric-label">购买概率</span>
              <span class="metric-value">{{ product.probability }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 营销建议 -->
    <div class="marketing-suggestions-section" v-if="prediction.recommendations">
      <h3>营销建议</h3>
      <div class="suggestions-list">
        <div 
          v-for="(suggestion, index) in prediction.recommendations" 
          :key="index"
          class="suggestion-item"
        >
          <el-icon class="suggestion-icon"><Lightbulb /></el-icon>
          <div class="suggestion-content">
            <h4>{{ getSuggestionTitle(suggestion) }}</h4>
            <p>{{ suggestion }}</p>
          </div>
          <div class="suggestion-priority">
            <el-tag :type="getSuggestionPriority(index)">
              {{ getPriorityText(index) }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 历史购买模式 -->
    <div class="purchase-pattern-section">
      <h3>历史购买模式</h3>
      <div class="pattern-analysis">
        <el-row :gutter="16">
          <el-col :span="8">
            <div class="pattern-card">
              <div class="pattern-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="pattern-content">
                <h4>{{ purchasePattern.frequency }}</h4>
                <p>购买频率</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="pattern-card">
              <div class="pattern-icon">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="pattern-content">
                <h4>{{ purchasePattern.seasonality }}</h4>
                <p>季节性偏好</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="pattern-card">
              <div class="pattern-icon">
                <el-icon><Star /></el-icon>
              </div>
              <div class="pattern-content">
                <h4>{{ purchasePattern.preference }}</h4>
                <p>品类偏好</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="createMarketingPlan">制定营销计划</el-button>
      <el-button @click="viewUserProfile">查看用户画像</el-button>
      <el-button @click="exportPredictionData">导出预测数据</el-button>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Lightbulb, Clock, Calendar, Star } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  prediction: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['create-marketing-plan', 'view-profile', 'export-data'])

// 计算属性
const timeConfidence = computed(() => {
  // 根据购买概率计算时间置信度
  return Math.round(props.prediction.purchaseProbability * 85)
})

const amountConfidence = computed(() => {
  // 根据购买概率计算金额置信度
  return Math.round(props.prediction.purchaseProbability * 78)
})

// 模拟数据
const recommendedProducts = computed(() => [
  {
    id: 1,
    name: 'iPhone 15 Pro',
    category: '电子产品',
    price: 7999,
    image: '/api/placeholder/80/80',
    recommendation: 4.5,
    probability: 89
  },
  {
    id: 2,
    name: '无线耳机',
    category: '电子产品',
    price: 299,
    image: '/api/placeholder/80/80',
    recommendation: 4.2,
    probability: 76
  },
  {
    id: 3,
    name: '智能手表',
    category: '电子产品',
    price: 2299,
    image: '/api/placeholder/80/80',
    recommendation: 4.0,
    probability: 68
  }
])

const purchasePattern = computed(() => ({
  frequency: '每月2-3次',
  seasonality: '春夏季偏好',
  preference: '电子产品'
}))

// 方法
const getIntentTagType = (intentLevel) => {
  const typeMap = {
    'High': 'success',
    'Medium': 'warning',
    'Low': 'danger'
  }
  return typeMap[intentLevel] || 'info'
}

const getIntentLevelText = (intentLevel) => {
  const textMap = {
    'High': '高意向',
    'Medium': '中意向',
    'Low': '低意向'
  }
  return textMap[intentLevel] || '未知'
}

const getPurchaseWindow = () => {
  const date = new Date(props.prediction.predictedDate)
  const startDate = new Date(date.getTime() - 3 * 24 * 60 * 60 * 1000)
  const endDate = new Date(date.getTime() + 3 * 24 * 60 * 60 * 1000)
  
  return `${startDate.toLocaleDateString()} - ${endDate.toLocaleDateString()}`
}

const getAmountRange = () => {
  const amount = props.prediction.predictedAmount
  const min = Math.round(amount * 0.8)
  const max = Math.round(amount * 1.2)
  
  return `¥${min.toLocaleString()} - ¥${max.toLocaleString()}`
}

const getImpactText = (impact) => {
  const textMap = {
    'high': '高影响',
    'medium': '中影响',
    'low': '低影响'
  }
  return textMap[impact] || '未知'
}

const getImpactColor = (impact) => {
  const colorMap = {
    'high': '#F56C6C',
    'medium': '#E6A23C',
    'low': '#67C23A'
  }
  return colorMap[impact] || '#909399'
}

const getSuggestionTitle = (suggestion) => {
  if (suggestion.includes('优惠券')) return '优惠策略'
  if (suggestion.includes('推荐')) return '产品推荐'
  if (suggestion.includes('客服')) return '客服关怀'
  return '营销建议'
}

const getSuggestionPriority = (index) => {
  const priorities = ['danger', 'warning', 'info']
  return priorities[index] || 'info'
}

const getPriorityText = (index) => {
  const texts = ['高优先级', '中优先级', '低优先级']
  return texts[index] || '普通'
}

const createMarketingPlan = () => {
  emit('create-marketing-plan', props.prediction)
}

const viewUserProfile = () => {
  emit('view-profile', props.prediction)
  ElMessage.info('跳转到用户画像页面')
}

const exportPredictionData = () => {
  emit('export-data', props.prediction)
  
  // 导出预测数据
  const data = {
    prediction: props.prediction,
    recommendedProducts: recommendedProducts.value,
    purchasePattern: purchasePattern.value,
    exportTime: new Date().toISOString()
  }
  
  const dataStr = JSON.stringify(data, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = `prediction_${props.prediction.userId}_detail.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  ElMessage.success('预测数据已导出')
}
</script>

<style scoped>
.prediction-detail-panel {
  padding: 20px 0;
}

.user-info-section,
.prediction-details-section,
.factors-section,
.recommended-products-section,
.marketing-suggestions-section,
.purchase-pattern-section {
  margin-bottom: 32px;
}

.user-info-section h3,
.prediction-details-section h3,
.factors-section h3,
.recommended-products-section h3,
.marketing-suggestions-section h3,
.purchase-pattern-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 8px;
}

/* 基本信息 */
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.info-item .label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.info-item .value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

/* 详情卡片 */
.detail-card {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  height: 100%;
}

.detail-card h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.time-analysis,
.amount-analysis {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.time-item,
.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-label,
.amount-label {
  font-size: 14px;
  color: #666;
  min-width: 80px;
}

.time-value,
.amount-value {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

/* 因子分析 */
.factors-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.factor-card {
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #ddd;
}

.factor-card.high {
  background: #fef2f2;
  border-left-color: #F56C6C;
}

.factor-card.medium {
  background: #fffbeb;
  border-left-color: #E6A23C;
}

.factor-card.low {
  background: #f0f9ff;
  border-left-color: #67C23A;
}

.factor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.factor-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.factor-impact {
  font-size: 12px;
  color: #666;
}

.factor-value {
  display: flex;
  align-items: center;
  gap: 12px;
}

.factor-value .el-progress {
  flex: 1;
}

.value-text {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  min-width: 40px;
}

/* 推荐产品 */
.products-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.product-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.product-category {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #666;
}

.product-price {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #f56c6c;
}

.product-metrics {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 120px;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #666;
}

.metric-value {
  font-size: 12px;
  font-weight: 600;
  color: #333;
}

/* 营销建议 */
.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 8px;
}

.suggestion-icon {
  color: #409EFF;
  font-size: 18px;
  margin-top: 2px;
}

.suggestion-content {
  flex: 1;
}

.suggestion-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.suggestion-content p {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.suggestion-priority {
  margin-top: 2px;
}

/* 购买模式 */
.pattern-analysis {
  margin-top: 16px;
}

.pattern-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
}

.pattern-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.pattern-content h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.pattern-content p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .factors-grid,
  .products-list {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .product-card {
    flex-direction: column;
    text-align: center;
  }
  
  .product-metrics {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
  }
}
</style>
